import { defineStore } from 'pinia';
import lodash from "lodash";
export interface RouteTab {
  name:string
  path:string
  title:string
}

export const useRouterTabStore = defineStore('routerTab', {
  state: () => ({
    currentIndex: '', // 当前的tab标识
    routeTabsList: [] as RouteTab[], // 记录需要展示在tab栏的路由
    deleteCurrentIndex: -1 as number,
    dynamicRoutes: [], // 动态路由列表
    isLoggedIn: <boolean>false // 登陆状态

  }),
    persist: {
      key: 'useRouterTabStore', //存储名称
      storage: localStorage, // 存储方式
      pick: [
       'currentIndex',
       'routeTabsList',
       'deleteCurrentIndex',
       'dynamicRoutes',
       'isLoggedIn'
      ]
    },
    getters: {},
    actions: {
      increment() {
      //   this.count++;
      },
      setCurrentIndex(currentIndex:string) {
          // 设置当前tab标识
          this.currentIndex = currentIndex
          // localStorage.setItem("currentIndex",currentIndex)
          
      },
      setDynamicRoutes (dynamicRoutesList: []) {
        this.dynamicRoutes = dynamicRoutesList
      },
      setLogInState (isLog: boolean) {
        this.isLoggedIn = isLog
      },
      addRouteTabsList(currentRoute:RouteTab) {
        
        let localRouteTabsListStr = localStorage.getItem("routeTabsList")?? ""
        let localRouteTabsList:RouteTab[] = localRouteTabsListStr ? JSON.parse(localRouteTabsListStr) : []
        let flag = localRouteTabsList && localRouteTabsList.some(item => item.name == currentRoute.name)
  
        if (!flag) {
          localRouteTabsList.push(currentRoute)
        } else {
          // 当name一样且路径不一致的数据去除掉
          let targetIndex = localRouteTabsList && localRouteTabsList.findIndex(item => item.name == currentRoute.name && item.path !== currentRoute.path)
          if (targetIndex !== -1) {
          localRouteTabsList.splice(targetIndex, 1, currentRoute);
          }
        }
        this.routeTabsList = [...localRouteTabsList]
        localStorage.setItem("routeTabsList",JSON.stringify(this.routeTabsList))
        
      },
      
      removeRouteTabsList(currentIndex:string) {
        // 移除当前路由
        lodash.remove(this.routeTabsList,(item,index) => {
          if (item.name === currentIndex) {
            this.deleteCurrentIndex = index > 0 ?index - 1 : 0
          }
          return item.name === currentIndex
        })
        localStorage.setItem("routeTabsList",JSON.stringify(this.routeTabsList))
        
      },
      clearRoute() {
        // 清空所有tab路由数据
        this.routeTabsList = []
        this.currentIndex = ""
        localStorage.removeItem("routeTabsList")
        localStorage.removeItem("currentIndex")
      }
    }
  })